﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace RBAC.Web.Utilities
{
    public enum sType { ASC, DESC };
    public static class Utilities
    {      
        public static string GetTextFromSelectListByValue(object id, SelectList input)
        {
            if (input != null && id != null)
                return input.First(i => i.Value == id.ToString()).Text;
            else
                return "";
        }

        public static void PrepareDateTimeProperity<TModel>(TModel model)
        {
            try
            {
                //Check ว่า model ที่เข้ามามี type DateTime ถ้ามี + year ไป 543
                Type type = model.GetType();
                PropertyInfo[] propertyInfo = type.GetProperties();
                foreach (PropertyInfo item in propertyInfo)
                {
                    if (item.PropertyType.Equals(typeof(DateTime)))
                    {
                        DateTime temp = (DateTime)item.GetValue(model, null);
                        if (temp.Equals(DateTime.MinValue))
                        {
                            temp = DateTime.Now;
                        }
                        if (temp.Year < 2443)
                            item.SetValue(model, temp.AddYears(543), null);
                    }
                }
            }
            catch { };
        }

		public static bool CheckNullOrEmpty<T>(T value)
        {
            if (typeof(T) == typeof(string))
                return !(string.IsNullOrEmpty(value as string));

            return !(value == null) || !(value.Equals(default(T)));
        }
    }

	public static class StringParser
    {
        public static T GetValue<T>(String value)
        {
            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                return default(T);
            }
        }
    }
}